﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace kxjsj
{
    class ImageUtil
    {
        public static byte[] ConvertBitmapToByteArr(Bitmap bitmap)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Jpeg);
                byte[] imgData = ms.ToArray();
                return imgData;
            }
        }

        public static Bitmap ConvertByteArrToBitmap(byte[] imgData)
        {
            if (imgData == null)
            {
                return null;
            }
            Image bitmap = null;
            using (MemoryStream ms = new MemoryStream(imgData))
            {
                bitmap = Image.FromStream(ms);
            }
            return GetCloneBitmap(bitmap);
            //return (Bitmap)bitmap.Clone();
            //return new Bitmap((Image)bitmap);
        }

        public static Bitmap GetCloneBitmap(Image bitmap)
        {
            Bitmap tempBmp = new Bitmap(bitmap.Width, bitmap.Height);
            Graphics draw = Graphics.FromImage(tempBmp);
            draw.DrawImage(bitmap, 0, 0);
            bitmap.Dispose();
            return tempBmp;
        }

        ///// <summary>
        ///// 压缩图片尺寸
        ///// </summary>
        ///// <param name="oldPath"></param>
        ///// <param name="zip"></param>
        ///// <param name="inner_id"></param>
        ///// <returns></returns>
        //public static Bitmap ZipImage(string oldPath, double zip, string inner_id)
        //{
        //    Image oldImage = Image.FromFile(oldPath);
        //    Bitmap bitmap = (Bitmap)oldImage;
        //    return ZipImage(bitmap, zip, inner_id);
        //}

        //public static Bitmap ZipImage(Bitmap oldBmp, double zip, string inner_id)
        //{
        //    int oldHeight = oldBmp.Height;
        //    int oldWidth = oldBmp.Width;
        //    int newWidth = (int)(zip * oldWidth);
        //    int newHeight = (int)(zip * oldHeight);

        //    Bitmap bmp = new Bitmap(newWidth, newHeight);
        //    string path = System.Windows.Forms.Application.StartupPath + "\\" + inner_id + "\\" + Guid.NewGuid().ToString() + ".jpg";
        //    Graphics grap = Graphics.FromImage(bmp);
        //    System.Drawing.Rectangle oldRect = new System.Drawing.Rectangle(0, 0, oldBmp.Width, oldBmp.Height);
        //    System.Drawing.Rectangle newRect = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);
        //    grap.InterpolationMode = InterpolationMode.HighQualityBilinear;
        //    grap.DrawImage(oldBmp, newRect, oldRect, GraphicsUnit.Pixel);
        //    return bmp;
        //}

        /// <summary>
        /// 压缩图片尺寸和清晰度
        /// </summary>
        /// <param name="oldPath"></param>
        /// <returns></returns>
        public static Bitmap ZipBitmap(Image oldImage, string inner_id)
        {
            Bitmap bitmap = (Bitmap)oldImage;
            double zip = 0;             //图片尺寸压缩比例,范围0~1
            if (oldImage.Height > oldImage.Width)
            {
                //竖版图片
                zip = Math.Min(1900.0 / oldImage.Height, 1200.0 / oldImage.Width);
            }
            else
            {
                //横版图片
                zip = Math.Min(1200.0 / oldImage.Height, 1900.0 / oldImage.Width);
            }
            string newPath = System.Windows.Forms.Application.StartupPath + "\\" + inner_id + "\\" + Guid.NewGuid().ToString() + ".jpg";
            GetPicThumbnail((System.Drawing.Image)bitmap, newPath, (int)(oldImage.Height * zip), (int)(oldImage.Width * zip), 100);        //压缩尺寸
            bitmap = new Bitmap(newPath);

            //byte[] bmArr = Common.ConvertBitmapToByteArr(bitmap);
            //if (bmArr.Length > 700000)
            //{
            //    //压缩清晰度
            //    newPath = System.Windows.Forms.Application.StartupPath + "\\" + inner_id + "\\" + Guid.NewGuid().ToString() + ".jpg";
            //    Common.GetPicThumbnail((System.Drawing.Image)bitmap, newPath, bitmap.Height, bitmap.Width, (int)(700000.0 / bmArr.Length));
            //    bitmap = new Bitmap(newPath);
            //}

            //bitmap.Save("G:\\原始图片" + Guid.NewGuid().ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            //int oldHeight = oldImage.Height;
            //int oldWidth = oldImage.Width;
            //double length = (double)Common.ConvertBitmapToByteArr(bitmap).Length;
            //if (oldHeight > 1200 || oldWidth > 1200)
            //{
            //    int big = Math.Max(oldHeight, oldWidth);
            //    double zip = 1200 / (double)big;
            //    bitmap = Common.ZipImage(oldPath, zip, inner_id);       //压缩尺寸
            //}

            //string path = System.Windows.Forms.Application.StartupPath + "\\" + inner_id + "\\" + Guid.NewGuid().ToString() + ".jpg";
            //Common.KiSaveAsJPEG(bitmap, path, 100);                    //压缩清晰度
            //Bitmap bmp = new Bitmap(path);
            //bmp.Save("G:\\压缩后图片" + Guid.NewGuid().ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            //return bmp;
            return bitmap;
        }

        /// <summary>
        /// 压缩图片尺寸和清晰度
        /// </summary>
        /// <param name="oldPath"></param>
        /// <returns></returns>
        public static Bitmap ZipBitmap(string oldPath, string inner_id)
        {
            Image oldImage = Image.FromFile(oldPath);
            return ZipBitmap(oldImage, inner_id);
        }


        #region GetPicThumbnail
        /// <summary>     
        /// 无损压缩图片     
        /// </summary>     
        /// <param name="sFile">原图片</param>     
        /// <param name="dFile">压缩后保存位置</param>     
        /// <param name="dHeight">高度</param>     
        /// <param name="dWidth"></param>     
        /// <param name="flag">压缩质量 1-100</param>     
        /// <returns></returns>       
        public static bool GetPicThumbnail(Image oldImage, string dFile, int dHeight, int dWidth, int flag)
        {
            //System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            System.Drawing.Image iSource = oldImage;
            ImageFormat tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            //按比例缩放        
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号       
            {
                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }
            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);
            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时，设置压缩质量    
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100     
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径  
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }
        #endregion

        ///// 判断图片是否需要压缩,如果图片大于500k或长宽之一大于560,则询问是否需要压缩
        ///// </summary>
        ///// <param name="oldPath">0:不需要压缩。1:需要压缩。-1:用户取消操作。</param>
        //public static int IsNeedZip(Image oldImage)
        //{
        //    Bitmap bitmap = (Bitmap)oldImage;
        //    int oldHeight = oldImage.Height;
        //    int oldWidth = oldImage.Width;

        //    double length = (double)ImageUtil.ConvertBitmapToByteArr(bitmap).Length;

        //    if ((length > 700000 && (oldImage.Height > oldImage.Width && (oldImage.Height > 1900 || oldImage.Width > 1200))) || (length > 700000 && (oldImage.Width > oldImage.Height && (oldImage.Height > 1200 && oldImage.Width > 1900))))
        //    //if (oldImage.Height > 1200 || oldImage.Width > 1200)
        //    {
        //        DialogResult dr = MessageBox.Show("上传文件大于500K，系统是否自动压缩图片并保存。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        //        if (dr == System.Windows.Forms.DialogResult.OK)
        //        {
        //            return 1;
        //        }
        //        else
        //        {
        //            MessageBox.Show("请自行压缩重新添加。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //            return -1;
        //        }
        //    }
        //    else
        //    {
        //        return 0;
        //    }
        //}

        public static Bitmap OpenImage(string fileName)
        {
            Bitmap dstImage = (Bitmap)Image.FromFile(fileName);
            return dstImage;
        }

        public static Image OpenImageWithFileStream(string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] buffer = new byte[fs.Length];
            int length = 0;
            int ibyteRead = 0;
            do
            {
                length = fs.Read(buffer, ibyteRead, buffer.Length - ibyteRead);
                ibyteRead += length;
            }
            while (length > 0);
            Image bitmap = Image.FromStream(fs);
            fs.Close();
            fs.Dispose();
            return bitmap;
        }

        /// 判断图片是否需要压缩,如果图片大于500k或长宽之一大于560,则询问是否需要压缩
        /// </summary>
        /// <param name="oldPath">0:不需要压缩。1:需要压缩。-1:用户取消操作。</param>
        public static int IsNeedZip(string oldPath)
        {
            //FileInfo info = new FileInfo(oldPath);
            double length = 0;
            //info.Create().Close();
            using (FileStream stream = File.Open(oldPath, FileMode.Open))
            {
                length = stream.Length;
            }
            Image oldImage = Image.FromFile(oldPath);
            Bitmap bitmap = (Bitmap)oldImage;
            int oldHeight = oldImage.Height;
            int oldWidth = oldImage.Width;

            int maxFileLength = 500 * 1024;     //图片文件不能超过500k

            //double length = (double)ImageUtil.ConvertBitmapToByteArr(bitmap).Length;

            if ((length > maxFileLength && (oldImage.Height > oldImage.Width && (oldImage.Height > 1900 || oldImage.Width > 1200))) || (length > maxFileLength && (oldImage.Width > oldImage.Height && (oldImage.Height > 1200 && oldImage.Width > 1900))))
            //if (oldImage.Height > 1200 || oldImage.Width > 1200)
            {
                DialogResult dr = MessageBox.Show("上传文件大于500K，系统是否自动压缩图片并保存。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == System.Windows.Forms.DialogResult.Yes)
                {
                    return 1;
                }
                else
                {
                    MessageBox.Show("请自行压缩重新添加。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return -1;
                }
            }
            else
            {
                return 0;
            }
        }

        ///**/
        ///// <summary>
        ///// 保存为JPEG格式，支持压缩质量选项
        ///// </summary>
        ///// <param name="bmp"></param>
        ///// <param name="FileName"></param>
        ///// <param name="Qty"></param>
        ///// <returns></returns>
        //public static bool KiSaveAsJPEG(Bitmap bmp, string FileName, int Qty)
        //{
        //    try
        //    {
        //        EncoderParameter p;
        //        EncoderParameters ps;
        //        ps = new EncoderParameters(1);
        //        p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
        //        ps.Param[0] = p;

        //        bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps);

        //        return true;
        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //}

        ///**/
        ///// <summary>
        ///// 保存JPG时用
        ///// </summary>
        ///// <param name="mimeType"></param>
        ///// <returns>得到指定mimeType的ImageCodecInfo</returns>
        //private static ImageCodecInfo GetCodecInfo(string mimeType)
        //{
        //    ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
        //    foreach (ImageCodecInfo ici in CodecInfo)
        //    {
        //        if (ici.MimeType == mimeType) return ici;
        //    }
        //    return null;
        //}
    }
}
